from PIL import ImageGrab
import cv2
import numpy as np
from com.wws.sw4sy.common import win32

# debugMode = True
debugMode = False
# 从截图查找图片,并返回在图片中的位置坐标
def mathc_img(x1,y1,x2,y2,Target, value=0.8):
    try:

        #全屏截图
        bbox = (x1,y1,x2,y2)
        im = np.array(ImageGrab.grab(bbox))
        # im = np.array(ImageGrab.grab())
        img_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
        #读取目标查找图片
        template = cv2.imread(Target, 0)
        #匹配，返回相似度
        res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
        threshold = value
        loc = np.where(res >= threshold)
        if debugMode:
            w, h = template.shape[::-1]
            for pt in zip(*loc[::-1]):
                cv2.rectangle(img_gray, pt, (pt[0] + w, pt[1] + h), (7, 249, 151), 2)

            cv2.imshow('Detected', img_gray)
            cv2.waitKey(0)
            cv2.destroyAllWindows()
        print(f"{int(loc[1][0])},{int(loc[0][0])}")
        return (int(loc[1][0]), int(loc[0][0]))
    except:
        raise Exception('未匹配到图片')
        # res(-1,-1)


#截图
#"I:\\pythonSolution\\projects\\sw4sy\\test\\winGui\\tmp.png"
def screenshot(x1,y1,x2,y2,img_save_path):
    bbox = (x1,y1,x2,y2)
    i = ImageGrab.grab(bbox)
    i.save(img_save_path)

    i = open(img_save_path, 'rb')
    img = i.read()
    return img

